package com.fishery.customization.controller;

import com.fishery.customization.entity.FunctionLabel;
import com.fishery.customization.entity.vo.UpdateFunctionLabelVo;
import com.fishery.customization.service.FunctionLabelService;
import com.fishery.entity.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/customization/function/label")
@Api(tags = "权限与标签映射管理模块")
@CrossOrigin
public class FunctionLabelController {

	@Autowired
	private FunctionLabelService functionLabelService;

	@PostMapping
	@ApiOperation("添加新权限标签(并未实现后续动态添加)")
	public Result addFunctionLabel(@RequestBody FunctionLabel functionLabel) {
		if (functionLabel == null
				|| StringUtils.isEmpty(functionLabel.getFunctionName())
				|| functionLabel.getLabel() == null
				|| functionLabel.getLabel().getChildren().isEmpty()) {
			return Result.error("添加失败");
		}
		return functionLabelService.saveFunctionLabel(functionLabel.getFunctionName(),
				functionLabel.getLabel()) ? Result.success("添加成功") : Result.error("添加失败");
	}

	@PutMapping
	@ApiOperation("修改权限标签（并未实现后续动态修改）")
	public Result updateFunctionLabel(@RequestBody UpdateFunctionLabelVo vo) {
		if (vo == null
				|| StringUtils.isEmpty(vo.getOldFunctionName())
				|| (vo.getLabel() == null || vo.getLabel().getChildren().isEmpty())
				&& StringUtils.isEmpty(vo.getNewFunctionName())) {
			return Result.error("修改失败");
		}
		return functionLabelService.updateFunctionLabel(vo.getOldFunctionName(), vo.getNewFunctionName(),
				vo.getLabel()) ? Result.success("修改成功") : Result.error("修改失败");
	}

	@DeleteMapping
	@ApiOperation("删除权限标签")
	public Result updateFunctionLabel(String functionName) {
		if (StringUtils.isEmpty(functionName)) {
			return Result.error("删除失败");
		}
		return functionLabelService.removeFunctionLabel(functionName)
				? Result.success("删除成功") : Result.error("删除失败");
	}

	@GetMapping
	@ApiOperation("查询出所有权限标签")
	public Result searchAllFunctionLabels() {
		return Result.success().data(functionLabelService.getAllFunctionLabels());
	}

	@GetMapping("/queryOne")
	@ApiOperation("通过权限名查询一级标签")
	public Result searchFunctionLabelWithFunctionName(String functionName) {
		if (StringUtils.isEmpty(functionName)) {
			return Result.error("查询失败");
		}
		return Result.success().data(functionLabelService.getOneLevelLabelByFunctionName(functionName));
	}
}
